package top.alanshelby.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import top.alanshelby.entity.Item;
import top.alanshelby.service.ItemService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class TestController {

    @Autowired
    private ItemService itemService;

    /**
     * 返回ModelAndView
     */
    @RequestMapping(value = "returnMV")
    public ModelAndView returnMV() {
        ModelAndView mv = new ModelAndView();
        List<Item> itemList = itemService.findItemList();
        mv.addObject("itemList", itemList);
        mv.setViewName("itemList");
        return mv;
    }

    /**
     * 返回void
     */
    @RequestMapping(value = "returnVoid")
    public void returnVoid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("findItem2 result");
    }

    /**
     * 返回字符串:逻辑视图名
     */
    @RequestMapping(value = "returnString")
    public String returnString(Model model) {
        List<Item> itemList = itemService.findItemList();
        model.addAttribute("itemList", itemList);
        return "itemList";
    }

    /**
     * 返回字符串:redirect重定向
     */
    @RequestMapping(value = "redirectUrl")
    public String redirectUrl() {
        System.out.println("代码执行到这里···redirectUrl");
        return null;
    }

    /**
     * 返回字符串:forward重定向
     */
    @RequestMapping(value = "forwardUrl")
    public String forwardUrl() {
        System.out.println("代码执行到这里···forwardUrl");
        return null;
    }

    /**
     * 测试redirect重定向和forward重定向
     */
    @RequestMapping(value = "test")
    public String test() {
        return "redirect:redirectUrl";
//        return "forward:forwardUrl";
    }

    /**
     * 返回json数据
     */
    @RequestMapping(value = "returnJson")
    public @ResponseBody List<Item> returnJson(Model model) {
        List<Item> itemList = itemService.findItemList();
        return itemList;
    }
}
